/* eslint-disable vue/no-side-effects-in-computed-properties */
/* eslint-disable @typescript-eslint/explicit-function-return-type */
/* eslint-disable camelcase */
import { computed, defineComponent, PropType, ref, VNode, watch } from 'vue';
import { useNamespace } from '@ibiz-template/vue3-util';
import { ControlVO, GridFieldColumnController } from '@ibiz-template/runtime';
import dayjs from 'dayjs';
import './checkin-grid-column.scss';

export const CheckInGridColumn = defineComponent({
  name: 'IBizCheckInGridColumn',
  props: {
    value: {
      type: Object as PropType<IData>,
      required: true,
    },
    data: {
      type: Object as PropType<ControlVO>,
      required: true,
    },
    controller: {
      type: Object as PropType<GridFieldColumnController>,
      required: true,
    },
    batch: {
      type: Boolean,
    },
    columnName: {
      type: String,
    },
    rowKey: {
      type: String,
    },
    selectionID: {
      type: String,
    },
  },
  setup(props) {
    const ns = useNamespace('checkin-column');

    const selected = ref('');

    watch(
      () => props.selectionID,
      () => {
        selected.value = props.selectionID || '';
      },
      {
        immediate: true,
      },
    );

    const timeToSeconds = (time: string) => {
      const date = dayjs(time);
      if (date.isValid()) {
        return date.unix();
      }
      const [h, m, s] = time.split(':').map(Number);
      return h * 3600 + m * 60 + s;
    };

    const getWorkTimes = (workTimes: IData[]) => {
      const item = workTimes.find(x => x.order_value === 1);
      if (item) {
        const { start_base_time, end_base_time } = item;
        // 次日时间判断
        if (timeToSeconds(start_base_time) > timeToSeconds(end_base_time)) {
          return `(${start_base_time}-次日${end_base_time})`;
        }
        return `(${start_base_time}-${end_base_time})`;
      }
    };

    const getTips = (workTimes: IData[]) => {
      return workTimes
        .map(item => {
          const { start_base_time, end_base_time } = item;
          // 次日时间判断
          if (timeToSeconds(start_base_time) > timeToSeconds(end_base_time)) {
            return `${start_base_time}-次日${end_base_time}`;
          }
          return `${start_base_time}-${end_base_time}`;
        })
        .join('\n');
    };

    const items = computed(() => {
      const { shifts = [], work_time = [] } = props.value || {};
      const { start_base_time, end_base_time } = work_time[0] || {};
      const startTime = start_base_time;
      const endTime = end_base_time;
      let timeUnit = '';
      if (startTime && endTime) {
        timeUnit = `(${startTime} - ${endTime})`;
      }
      const restDay = {
        title: `休息`,
        value: 'rest',
        name: '休息',
      };
      const workday = {
        title: `白班${timeUnit}`,
        value: 'work',
        name: '白班',
      };
      // 无选项数据
      if (!shifts.length) {
        return [workday, restDay];
      }
      const result = shifts.map((item: IData) => {
        const { name, work_times } = item.shift_data;
        const time = getWorkTimes(work_times);
        const tips = getTips(work_times);
        return {
          title: `${name}${time}`,
          value: item.id,
          name,
          tips,
          origin: item,
        };
      });
      return [...result, restDay];
    });

    const curTips = ref('');

    const curValue = computed(() => {
      const { workday, shift_data } = props.value || {};
      if (!workday) {
        const restDay = items.value.find(item => item.value === 'rest');
        if (restDay) {
          return restDay.title;
        }
        return '休息';
      }
      if (shift_data) {
        const name = shift_data.name;
        const shift = items.value.find(item => item.name === name);
        if (shift) {
          curTips.value = shift.tips;
          return shift.title;
        }
        return name;
      }
      return '';
    });

    const selectValue = computed(() => {
      if (selected.value) {
        const item = items.value.find((x: IData) => x.value === selected.value);
        if (item) {
          curTips.value = item.tips;
          return item.title;
        }
      }
      return '';
    });

    const handleClick = async (command: string) => {
      if (!props.value) {
        return;
      }
      const { grid } = props.controller as IData;
      const item = items.value.find((x: IData) => x.value === command);
      if (item.title === curValue.value) {
        selected.value = '';
        if (props.batch) {
          grid.batchRemoveCheckInData(props.columnName);
        } else {
          grid.removeCheckInData(props.value.id);
        }
      } else {
        selected.value = command;
        if (props.batch) {
          grid.setBatchCheckInData(props.columnName, {
            id: props.value.id,
            workday: command !== 'rest' ? 1 : 0,
            choose_shift: item.origin,
          });
        } else {
          grid.setCheckInData(props.value.id, {
            id: props.value.id,
            workday: command !== 'rest' ? 1 : 0,
            choose_shift: item.origin,
          });
        }
      }
    };
    return {
      ns,
      curValue,
      selectValue,
      curTips,
      items,
      selected,
      handleClick,
    };
  },
  render() {
    if (!this.value) {
      return <div class={this.ns.e('empty')}>/</div>;
    }
    const caption = this.selectValue || this.curValue;
    return (
      <el-dropdown
        onCommand={(command: string): Promise<void> =>
          this.handleClick(command)
        }
        class={[
          this.ns.b(),
          this.ns.m(this.controller.grid.overflowMode),
          this.controller.model.cellSysCss?.cssName,
          this.ns.m('dropdown'),
          this.ns.is('active', !!this.selected),
          this.ns.is('manual', this.value.manual),
        ]}
        popper-class={this.ns.b('popper')}
        trigger='click'
      >
        {{
          default: (): VNode => (
            <span class={this.ns.e('caption')}>
              {caption !== '休息' ? (
                <el-tooltip placement='top'>
                  {{
                    default: () => {
                      return caption.replace(/\(.*\)/g, '');
                    },
                    content: () => {
                      return (
                        <div class={this.ns.e('tooltip')}>
                          {
                            <div class={this.ns.e('tooltip-title')}>
                              {caption.replace(/\(.*\)/g, '')}:
                            </div>
                          }
                          <div class={this.ns.e('tooltip-content')}>
                            {this.curTips}
                          </div>
                        </div>
                      );
                    },
                  }}
                </el-tooltip>
              ) : (
                caption.replace(/\(.*\)/g, '')
              )}
            </span>
          ),
          dropdown: (): VNode => (
            <el-dropdown-menu>
              {this.items.map(item => {
                return (
                  <el-dropdown-item
                    class={[this.ns.e('item')]}
                    title={item.title}
                    command={item.value}
                    disabled={
                      item.title === (this.selectValue || this.curValue)
                    }
                  >
                    {item.title !== '休息' ? (
                      <el-tooltip placement='top'>
                        {{
                          default: () => {
                            return item.title;
                          },
                          content: () => {
                            return (
                              <div class={this.ns.e('tooltip')}>
                                <div class={this.ns.e('tooltip-title')}>
                                  {item.title.replace(/\(.*\)/g, '')}:
                                </div>
                                <div class={this.ns.e('tooltip-content')}>
                                  {item.tips}
                                </div>
                              </div>
                            );
                          },
                        }}
                      </el-tooltip>
                    ) : (
                      item.title
                    )}
                  </el-dropdown-item>
                );
              })}
            </el-dropdown-menu>
          ),
        }}
      </el-dropdown>
    );
  },
});
export default CheckInGridColumn;
